package com.dongdongshop.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.dongdongshop.data.Result;
import com.dongdongshop.em.ResultEnum;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Controller
@RequestMapping("test")
public class FileController {

    @RequestMapping("upload")
    @ResponseBody
    public Result upload(@RequestParam("myFile") MultipartFile myFile) {
        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String http = "https://";
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tQMtY2T9Z3LLf1DEk3W";
        String accessKeySecret = "Oa5Qqg5bvQDXXBxSmjWOHiAz7h3gka";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "2015dongdongshop";
        String objectName = "image/" + myFile.getOriginalFilename();
        // 填写文件名。文件名包含路径，不包含Bucket名称。例如exampledir/exampleobject.txt。
//        String objectName = "image/test.text";

        OSS ossClient = null;
        try {
            // 创建OSSClient实例。
            ossClient = new OSSClientBuilder().build(http + endpoint, accessKeyId, accessKeySecret);

//            String content = "Hello OSS";
            ossClient.putObject(bucketName, objectName, myFile.getInputStream());
        } catch (OSSException | IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }
//        https://2015dongdongshop.oss-cn-beijing.aliyuncs.com/516883e7-9757-4cb5-9e64-84ea7255912f.jpg
        String url= http + bucketName + "." + endpoint + "/" + objectName;
        return Result.response(ResultEnum.SUCCESS).setData(url);
    }

}
